#region References

using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using SpoolFileLibrary.Reader.Winspool;

#endregion

namespace SpoolFileLibrary.Reader.Misc {
    internal static class ParsingHelper {
        public static T ConvertToStruct<T>(byte[] data) {
            GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);
            var dataStruct = (T) Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T));
            handle.Free();
            return dataStruct;
        }

        public static unsafe DEVMODE ExtractDevMode(BinaryReader binaryReader, int offset) {
            binaryReader.BaseStream.Seek(offset, SeekOrigin.Begin);
            var buffer = new byte[sizeof(DEVMODE)];
            binaryReader.BaseStream.Read(buffer, 0, buffer.Length);

            return new DEVMODE(buffer);
        }

        public static string ReadString(BinaryReader binaryReader, int offset) {
            binaryReader.BaseStream.Seek((long)offset, SeekOrigin.Begin);
            var str = string.Empty;
            while (true) {
                var ch = binaryReader.ReadChar();
                if (ch == '\0') {
                    return str;
                }
                str = str + ch;
            }
        }

        public static string ReadString(BinaryReader binaryReader, int offset, int length) {
            binaryReader.BaseStream.Seek((long)offset, SeekOrigin.Begin);
            var chArray = binaryReader.ReadChars(length);
            return chArray.Where(ch => ch != '\0').Aggregate(string.Empty, (current, ch) => current + ch);
        }
    }
}